package com.lazydong.apiforward.client;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.lazydong.apiforward.client.framework.PageContainer;
import com.lazydong.apiforward.client.framework.util.RunCmdUtil;
import com.lazydong.apiforward.client.gui.constant.CommonConstant;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * Api转发工具
 */
public class ApiForwardClient {
    private static final String PID_FILE = CommonConstant.CURRENT_DIR + File.separator + "ApiForwardClient.pid";

    public static void main(String[] args) {
        if (FileUtil.exist(PID_FILE)) {
            String pid = FileUtil.readString(PID_FILE, StandardCharsets.UTF_8);
            if (RunCmdUtil.checkPid(pid)) {
                // 有程序再运行
                System.exit(0);
            }
        }
        killUpdate();
        String pid = String.valueOf(RuntimeUtil.getPid());
        FileUtil.writeString(pid, PID_FILE, StandardCharsets.UTF_8);
        // 关闭
        PageContainer.initialize("com.lazydong.apiforward.client.gui.pages");
    }

    public static void delPid() {
        FileUtil.del(PID_FILE);
    }

    private static void killUpdate() {
        if (!FileUtil.exist(CommonConstant.UPDATE_PID)) {
            return;
        }
        String pid = FileUtil.readString(CommonConstant.UPDATE_PID, StandardCharsets.UTF_8);
        RunCmdUtil.killByPid(pid);
    }
}
